package meadproperty.popup.actions;

import java.io.File;

import meadproperty.service.Config;
import meadproperty.service.Constant;
import meadproperty.util.FileUtil;
import meadproperty.views.PropertyViewer;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

public class OpenAction implements IObjectActionDelegate {
	private static IStructuredSelection select;
	private Shell shell;

	public OpenAction() {
		super();
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	public void run(IAction action) {
		IFile file = (IFile) select.getFirstElement();
		String path = file.getFullPath().toOSString();
		String configFileAllPath = path;

		int index = path.lastIndexOf('\\');
		String fileName = path.substring(index);
		path = path.substring(0, index);

		if (fileName.contains(Constant.FILE_NAME_CONFIG)) {
			Constant.ACTIVE_FILE_NAME = fileName;
			path = Constant.WORK_SPACE_PATH + path;
			Constant.ACTIVE_FILE_PATH = FileUtil.getOSFilePath(path)
					+ File.separatorChar;
			Constant.ACTIVED_MARK = true;

		} else {
			Constant.ACTIVED_MARK = false;
			Constant.ACTIVE_FILE_PATH = "";
			Constant.ACTIVE_FILE_NAME = "";
			Constant.ACTIVE_CONFIG = new Config();
			MessageDialog.openInformation(shell, "ERROR: config file:",
					"ERROR: config file:" + fileName);
			return;
		}
		Config cfg = new Config().fromXML();
		Constant.ACTIVE_CONFIG = cfg;
		Constant.ACTIVED_MARK = true;
		MessageDialog.openInformation(shell, "ACTIVE_FILE_PATH",
				Constant.ACTIVE_FILE_PATH);
		String wsPath = Constant.WORK_SPACE_PATH;
		MessageDialog.openInformation(shell, "config.xml",
				Constant.ACTIVE_FILE_PATH + Constant.FILE_NAME_CONFIG);
		if (Constant.PLUG_IN_VIEW_STATE == Constant.PLUG_IN_VIEW_STATE_OPEN) {
			IViewPart view = PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow().getActivePage().findView(
							PropertyViewer.ID);
			PropertyViewer my = (PropertyViewer)view;
			my.reFresh();
			System.err.println("reDraw###############");

		}
		try {
			PlatformUI.getWorkbench().getActiveWorkbenchWindow()
					.getActivePage().showView(PropertyViewer.ID);
			Constant.PLUG_IN_VIEW_STATE = Constant.PLUG_IN_VIEW_STATE_OPEN;
		} catch (PartInitException e) {
			MessageDialog.openInformation(shell, "EXCEPTION",
					Constant.ACTIVE_FILE_PATH);
		}

	}

	public void selectionChanged(IAction action, ISelection selection) {
		select = (IStructuredSelection) selection;
	}

}
